//
//  ViewController.swift
//  uploadMorePictures
//
//  Created by 李龙 on 15/3/23.
//  Copyright (c) 2015年 Lauren. All rights reserved.
//


import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //上传文件
        uploadFiles()
        
    }
    
    
    //AFN创建boundary的方法
    lazy var boundary: String? = {
        return String(format: "%08x%08x", arguments: [arc4random(), arc4random()])
        }()
    
    // 测试上传多个文件
    func uploadFiles() {
        
        let data1 = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("a.png", ofType: nil)!)!
        let data2 = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("b.png", ofType: nil)!)!
        
        
        let httpData = formData(nil, fieldName: "userfile[]", dataList: [data1, data2], filenames: ["aa88.png", "bb99.png"])
        
        // 1. url
        let url = NSURL(string: "http://localhost/post/upload-m.php")!
        var request = NSMutableURLRequest(URL: url)
        //这个boundary前边的 不多"--"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = "POST"
        // 如果是 uploadTask，不需要设置 body
        //        request.HTTPBody = httpData
        // 2. session
        // dataTask 上传
        //        NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (_, response, _) -> Void in
        //
        //            println(response)
        //        }).resume()
        
        
        NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: httpData) { (_, response, _) -> Void in
            println(response)
            }.resume()
    }
    
    
    ///  生成要上传给服务器的二进制数据 (multipart/form-data)
    ///
    ///  :param: params    <#params description#>
    ///  :param: fieldName 字段名
    ///  :param: dataList  要上传的二进制文件数据
    ///  :param: filenames 上传后的名字
    ///
    ///  :returns: post上传二进制文件数据的完整格式
    func formData(params: [String: String]?, fieldName: String, dataList: [NSData], filenames: [String]) -> NSData {
        var httpBody = NSMutableData()
        
        // 1. 拼接要上传给服务器的参数
        if params != nil {
            for (k, v) in params! {
                //这个boundary前边的 “--”多两个
                var bodyStr = "--\(boundary)\r\n"
                bodyStr += "Content-Disposition: form-data; name=\"\(k)\";\r\n\r\n"
                //把上边的字符串拼接到httpBody中
                // dataUsingEncoding:allowLossyConversion:   返回指定编码的NSData对象，可以选择无损转化
                httpBody.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
                httpBody.appendData(v.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
                httpBody.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            }
        }
        // 2. 拼接要上传的二进制文件数据
        var index = 0
        for data in dataList {
            var bodyStr = "--\(boundary)\r\n"
            bodyStr += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(filenames[index])\"\r\n"
            //一般这里写octet-stream：八进制的数据流。 一般不让服务器管这里是什么格式就这么写。
            //实际上我们随便写都可以
            bodyStr += "Content-Type: application/octet-stream\r\n\r\n"
            
            //继续拼接到httpBody上
            httpBody.appendData(bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            httpBody.appendData(data)
            httpBody.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            
            index++ //叠加数据
        }
        
        // 3. 收尾字符串
        httpBody.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        
        return httpBody
    }
}


